<!-- 收货单统计页面 -->
<template>
  <div class="receipt-statistics-container">
    <div class="page-header">
      <h2>收货单统计</h2>
      <div class="header-actions">
        <el-date-picker
            v-model="selectedYear"
            :clearable="false"
            format="YYYY"
            placeholder="选择年份"
            type="year"
            value-format="YYYY"
            @change="handleYearChange"
        />
        <el-button type="primary" @click="refreshData">刷新数据</el-button>
      </div>
    </div>

    <!-- 加载指示器 -->
    <div v-if="loading" class="loading-container">
      <el-icon :size="32" class="loading-icon">
        <Loading/>
      </el-icon>
      <p>加载统计数据中...</p>
    </div>

    <!-- 统计卡片区域 -->
    <el-row v-loading="loading" :gutter="20" class="stat-cards">
      <el-col :md="8" :sm="12" :xs="24">
        <el-card class="stat-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>收货单总数</span>
            </div>
          </template>
          <div class="stat-value">{{ overallStats.totalCount || 0 }}</div>
          <div class="stat-subtext">本月新增：{{ overallStats.currentMonthCount || 0 }}</div>
        </el-card>
      </el-col>
      <el-col :md="8" :sm="12" :xs="24">
        <el-card class="stat-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>收货总金额</span>
            </div>
          </template>
          <div class="stat-value">¥{{ formatAmount(overallStats.totalAmount) }}</div>
          <div class="stat-subtext">本月金额：¥{{ formatAmount(overallStats.currentMonthAmount) }}</div>
        </el-card>
      </el-col>
      <el-col :md="8" :sm="12" :xs="24">
        <el-card class="stat-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>验收率</span>
            </div>
          </template>
          <div class="stat-value">{{ overallStats.acceptanceRate || 0 }}%</div>
          <div class="stat-subtext">已验收/总数</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 收货单状态分布 -->
    <el-row :gutter="20" class="chart-section">
      <el-col :md="12" :xs="24">
        <el-card v-loading="loading" class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>验收状态分布</span>
            </div>
          </template>
          <div id="statusChart" ref="statusChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :md="12" :xs="24">
        <el-card v-loading="loading" class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>月度收货金额趋势</span>
              <span class="subtitle">(按收货日期统计)</span>
            </div>
          </template>
          <div id="trendChart" ref="trendChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 供应商TOP5 -->
    <el-card v-loading="loading" class="chart-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>供应商TOP5（按收货金额）</span>
        </div>
      </template>
      <el-table :data="supplierTop5" stripe style="width: 100%">
        <el-table-column align="center" type="index" width="50"/>
        <el-table-column label="供应商" min-width="180" prop="supplierName"/>
        <el-table-column align="center" label="收货单数量" width="120">
          <template #default="scope">
            {{ scope.row.count }}
          </template>
        </el-table-column>
        <el-table-column align="right" label="收货金额" min-width="150">
          <template #default="scope">
            ¥{{ formatAmount(scope.row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="占比" width="100">
          <template #default="scope">
            {{ calculatePercentage(scope.row.totalAmount, supplierTotalAmount) }}%
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script lang="ts">
import {computed, defineComponent, nextTick, onMounted, ref} from 'vue';
import * as echarts from 'echarts';
import {ElMessage} from 'element-plus';
import {Loading} from '@element-plus/icons-vue';
import {getReceiptStatistics} from '@/api/statistics';

export default defineComponent({
  name: 'ReceiptStatistics',
  components: {
    Loading
  },
  setup() {
    // 图表实例
    let statusChartInstance: echarts.ECharts | null = null;
    let trendChartInstance: echarts.ECharts | null = null;

    // 加载状态
    const loading = ref(true);

    // 整体统计数据
    const overallStats = ref<any>({});

    // 供应商数据
    const supplierTop5 = ref<any[]>([]);
    const supplierTotalAmount = computed(() => {
      if (!supplierTop5.value.length) return 0;
      return supplierTop5.value.reduce((sum, item) => sum + parseFloat(item.totalAmount || 0), 0);
    });

    // 年份选择
    const selectedYear = ref<number>(new Date().getFullYear());

    // 格式化金额
    const formatAmount = (amount: any): string => {
      if (amount === undefined || amount === null) return '0.00';
      return parseFloat(amount).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    };

    // 计算百分比
    const calculatePercentage = (value: number, total: number): string => {
      if (!total) return '0.00';
      return ((value / total) * 100).toFixed(2);
    };

    // 初始化状态饼图
    const initStatusChart = () => {
      // 如果存在旧的图表实例，先销毁它
      if (statusChartInstance) {
        statusChartInstance.dispose();
        statusChartInstance = null;
      }

      // 如果没有状态统计数据，则使用默认数据
      if (!overallStats.value.statusStats || !overallStats.value.statusStats.length) {
        // 创建默认的饼图数据
        const defaultData = [
          {name: '待验收', value: 0},
          {name: '已验收', value: 0}
        ];

        const chartDom = document.getElementById('statusChart');
        if (!chartDom) return;

        statusChartInstance = echarts.init(chartDom);

        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            data: defaultData.map(item => item.name)
          },
          series: [
            {
              name: '验收状态',
              type: 'pie',
              radius: ['50%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: true,
                formatter: '{b}: {c} ({d}%)'
              },
              emphasis: {
                label: {
                  show: true,
                  fontWeight: 'bold'
                }
              },
              data: defaultData
            }
          ]
        };

        statusChartInstance.setOption(option);
        return;
      }

      const chartDom = document.getElementById('statusChart');
      if (!chartDom) return;

      statusChartInstance = echarts.init(chartDom);

      const chartData = overallStats.value.statusStats.map((item: any) => ({
        name: item.status || '未知',
        value: parseInt(item.count)
      }));

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: chartData.map((item: any) => item.name)
        },
        series: [
          {
            name: '验收状态',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}: {c} ({d}%)'
            },
            emphasis: {
              label: {
                show: true,
                fontWeight: 'bold'
              }
            },
            data: chartData
          }
        ]
      };

      statusChartInstance.setOption(option);
    };

    // 初始化趋势图
    const initTrendChart = () => {
      // 如果存在旧的图表实例，先销毁它
      if (trendChartInstance) {
        trendChartInstance.dispose();
        trendChartInstance = null;
      }

      // 如果没有月度趋势数据，使用默认数据
      if (!overallStats.value.monthlyTrend || !overallStats.value.monthlyTrend.length) {
        const chartDom = document.getElementById('trendChart');
        if (!chartDom) return;

        trendChartInstance = echarts.init(chartDom);

        const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
        const amountData = new Array(12).fill(0);
        const countData = new Array(12).fill(0);

        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          legend: {
            data: ['金额', '数量']
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: months
          },
          yAxis: [
            {
              type: 'value',
              name: '金额',
              axisLabel: {
                formatter: '{value}元'
              }
            },
            {
              type: 'value',
              name: '数量',
              axisLabel: {
                formatter: '{value}个'
              }
            }
          ],
          series: [
            {
              name: '金额',
              type: 'bar',
              data: amountData
            },
            {
              name: '数量',
              type: 'line',
              yAxisIndex: 1,
              data: countData
            }
          ]
        };

        trendChartInstance.setOption(option);
        return;
      }

      const chartDom = document.getElementById('trendChart');
      if (!chartDom) return;

      trendChartInstance = echarts.init(chartDom);

      const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
      const amountData = new Array(12).fill(0);
      const countData = new Array(12).fill(0);

      overallStats.value.monthlyTrend.forEach((item: any) => {
        // 解析月份格式 "YYYY-MM"
        if (item.month && typeof item.month === 'string') {
          const monthParts = item.month.split('-');
          if (monthParts.length === 2) {
            const monthIndex = parseInt(monthParts[1]) - 1; // 取得月份部分并减1得到索引
            if (monthIndex >= 0 && monthIndex < 12) {
              // 使用totalAmount字段（后端返回的字段名）
              amountData[monthIndex] = parseFloat(item.totalAmount || 0);
              // 修改这里：使用 count 字段，如果不存在则使用 0
              countData[monthIndex] = parseInt(item.count || 0);
            }
          }
        }
      });

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['金额', '数量']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: months
        },
        yAxis: [
          {
            type: 'value',
            name: '金额',
            axisLabel: {
              formatter: '{value}元'
            }
          },
          {
            type: 'value',
            name: '数量',
            axisLabel: {
              formatter: '{value}个'
            }
          }
        ],
        series: [
          {
            name: '金额',
            type: 'bar',
            data: amountData
          },
          {
            name: '数量',
            type: 'line',
            yAxisIndex: 1,
            data: countData
          }
        ]
      };

      trendChartInstance.setOption(option);
    };

    // 初始化所有图表
    const initCharts = async () => {
      await nextTick();
      initStatusChart();
      initTrendChart();

      // 监听窗口变化，重绘图表
      window.addEventListener('resize', () => {
        statusChartInstance?.resize();
        trendChartInstance?.resize();
      });
    };

    // 获取收货单统计数据
    const fetchReceiptStats = async () => {
      try {
        loading.value = true;

        // 构建API参数
        const params: any = {
          year: selectedYear.value
        };

        // 调用统计API
        const response = await getReceiptStatistics(params);

        if (response && response.code === 200 && response.data) {
          // 处理API返回的数据
          overallStats.value = {
            totalCount: response.data.totalCount || 0,
            totalAmount: response.data.totalAmount || 0,
            currentMonthCount: response.data.currentMonthCount || 0,
            currentMonthAmount: response.data.currentMonthAmount || 0,
            acceptanceRate: calculateAcceptanceRate(response.data),
            // 如果需要，可以添加默认值或空数组
            statusStats: response.data.statusStats || [],
            monthlyTrend: response.data.monthlyTrend || [],
            supplierTop5: response.data.supplierTop5 || []
          };

          // 仅当后端返回了供应商数据时才更新
          if (response.data.supplierTop5 && response.data.supplierTop5.length > 0) {
            supplierTop5.value = response.data.supplierTop5;
          } else {
            // 使用空数组作为默认值
            supplierTop5.value = [];
          }

          // 初始化图表
          initCharts();
        } else {
          ElMessage.error('获取统计数据失败');
          console.error('获取统计数据失败：', response);
        }
      } catch (error) {
        console.error('获取收货单统计数据失败', error);
        ElMessage.error('获取统计数据失败，请稍后重试');
      } finally {
        loading.value = false;
      }
    };

    // 处理年份变化
    const handleYearChange = () => {
      refreshData();
    };

    // 刷新所有数据
    const refreshData = async () => {
      loading.value = true;
      try {
        await fetchReceiptStats();
      } catch (error) {
        console.error('刷新数据失败', error);
      } finally {
        loading.value = false;
      }
    };

    // 计算验收率
    const calculateAcceptanceRate = (data: any): number => {
      if (!data) return 0;

      // 如果后端直接返回了验收率
      if (data.acceptanceRate !== undefined) return data.acceptanceRate;

      // 如果有状态统计，计算验收率
      if (data.statusStats && data.statusStats.length > 0) {
        const accepted = data.statusStats.find((s: any) => s.status === '已验收');
        const acceptedCount = accepted ? accepted.count : 0;

        if (data.totalCount && data.totalCount > 0) {
          return Math.round((acceptedCount / data.totalCount) * 100);
        }
      }

      return 0;
    };

    // 组件挂载时初始化
    onMounted(() => {
      refreshData();
    });

    return {
      loading,
      overallStats,
      supplierTop5,
      supplierTotalAmount,
      selectedYear,
      formatAmount,
      calculatePercentage,
      handleYearChange,
      refreshData
    };
  }
});
</script>

<style scoped>
.receipt-statistics-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
}

.loading-icon {
  animation: loading-rotate 2s linear infinite;
}

@keyframes loading-rotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  margin-bottom: 20px;
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 10px;
}

.stat-subtext {
  font-size: 14px;
  color: #909399;
}

.chart-section {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.chart-actions {
  display: flex;
  gap: 10px;
}

#statusChart, #trendChart {
  height: 300px;
  width: 100%;
}

.subtitle {
  font-size: 12px;
  color: #909399;
  margin-left: 10px;
}

.year-hint {
  font-size: 13px;
  color: #909399;
  margin-right: 10px;
}
</style> 